<?php


namespace app\api\logic;


use app\api\model\Merchant as MerchantModel;
use app\api\model\Airport as AirportModel;
use app\api\model\Posts as PostsModel;
use app\api\model\Area as AreaModel;
use app\api\model\Category as CategoryModel;
use think\facade\Cache;

class Index
{
    private $merchantModel;
    private $airportModel;
    private $postsModel;

    public function __construct(MerchantModel $merchantModel,AirportModel $airportModel,PostsModel $postsModel)
    {
        $this->merchantModel=$merchantModel;
        $this->airportModel=$airportModel;
        $this->postsModel=$postsModel;
    }

    /**
     * 逻辑判断
     * 1.已登录   商户关联机场
     * 2.未登录   开启定位；取500km最近的机场，
     *              没有最近机场  取最后一次选择的机场
     *                没有最后一次选择的机场  先获取定位所在国家的所有机场
     *                  所在国家没记录  拉起所有国家关联机场数据
     *           未开启定位：取最后一次选择的机场
     *             没有最后一次选择的机场 取定位所在国家
     *               国家也获取不到 拉起所有国家关联机场数据
     *
     * @param $params
     */
    public function handle($params){
        $airport=0;
        $handler=Cache::store('redis')->handler();
        $data=$handler->georadius(config('redis.redis_key.airport_location'),$params['lon'],$params['lat'],500,'km',['COUNT'=>1]);
        if($data){
            $info=explode('_',$data[0]);
            $airport=end($info);
            return $airport;
        }
        //返回最后一次用户选择的机场
        //if($params['airport']) return $params['airport'];
        return $airport;
    }


    /**
     *
     * 筛选条件
     * 1.terminal
     * 2.category   sub_category
     * 3.Envent time  today、tomorrow、next 3 day、add dates
     * 4. keyword
     * 发布时间降序排列
     * @param $params
     */
    public function posts($params){
        $where[]=['p.status','=',1];
        $where[]=['m.airport','=',$params['airport']];
        $where[]=['m.status','>=',0];
//        if($params['terminal']) $where[]=['m.terminal','=',$params['terminal']];
        if($params['category']) $where[]=['m.category','=',$params['category']];
//        if($params['keyword']) $where[]=['p.title','LIKE','%'.$params['keyword'].'%'];
        $timeZone=$this->airportModel->getTimeZone($params['airport']);
        if($params['deadline']){
            $deadline=explode(' ',$params['deadline']);
            $start_time=$deadline[0];
            $end_time=$deadline[1];
//            $real_start_time=strtotime($start_time)-($timeZone*3600);
            $real_end_time=strtotime($end_time)+(3600*24);
            $params['real_start_time']=$start_time;
            $params['real_end_time']=date('Y-m-d H:i:s',$real_end_time);
            $params['timeZone']=$timeZone;
        }
        $res=$this->postsModel->index($params,$where);
        //返回筛选信息
//        $airportInfo=$this->getAirportInfo($params['airport']);
//        $res['iata']=$airportInfo['iata'];
//        $res['country_id']=$airportInfo['country_id'];
//        $res['city_id']=$airportInfo['city_id'];
//        $res['country_name']=$airportInfo['country_name'];
//        $res['city_name']=$airportInfo['city_name'];
//        $res['airport_id']=$airportInfo['airport_id'];
//        if($params['terminal']){
//            //处理多选项
//            $terminals=explode(',',$params['terminal']);
//            if(count($terminals)>2){
//                $res['terminal_str']=current($terminals).'..'.end($terminals);
//            }else{
//                $res['terminal_str']=$params['terminal'];
//            }
//        }else{
//            $res['terminal_str']='';
//        }
//        $terminals=$this->airportModel->where('id',$params['airport'])->value('terminal');
//        $res['terminals']=json_decode($terminals,true);
//        $res['terminal']=$params['terminal']?explode(',',$params['terminal']):$res['terminals'];
        if($res['total']>0){
//            if(!isset($params['userID'])){
//                $params['userID']=0;
//            }
            $res['result']=Posts::handleData($res['result'],$params['userID'],$timeZone);
        }

        return $res;
    }

    public function getAirportInfo($airport_id){
        $airportInfo=$this->airportModel->where('id',$airport_id)->field('country,city,iata,terminal,name')->find()->toArray();
        $res['iata']=$airportInfo['iata'];
        $res['country_id']=$airportInfo['country'];
        $res['city_id']=$airportInfo['city'];
        $res['country_name']=AreaModel::where('id',$res['country_id'])->value('name');
        $res['abbreviation']=AreaModel::where('id',$res['country_id'])->value('abbreviation');
        $res['city_name']=AreaModel::where('id',$res['city_id'])->value('name');
        $res['airport_id']=intval($airport_id);
        $res['terminals']=json_decode($airportInfo['terminal'],true);
        $res['terminal']=$res['terminals'];
        $res['airport_name']=$airportInfo['name'];
        return $res;
    }

    /**
     * 筛选条件
     * keyword category
     * @param $params
     */
    public function merchants($params){
        $where[]=['status','>=',0];
        $where[]=['airport','=',$params['airport']];
        if($params['keyword']) $where[]=['m.name|c.name','LIKE','%'.$params['keyword'].'%'];
        if($params['category']) $where[]=['category','=',$params['category']];
        $data=$this->merchantModel->index($params,$where);
        $timeZone=$this->airportModel->getTimeZone($params['airport']);
        if($data['total']>0){
            foreach ($data['result'] as $key=>$val){
                $data['result'][$key]['avatar']=getMerchantAvatar($val['avatar']);

                $data['result'][$key]['open_status']=merchantStatus($timeZone,$val);

                if($val['category']){
                    $data['result'][$key]['category']=CategoryModel::where('id',$val['category'])->value('name');
                }
                $data['result'][$key]['week']=json_decode($val['week']);
                $sub_categories=[];
                if($val['sub_category']){
                    $sub_category=explode(',',$val['sub_category']);

                    foreach ($sub_category as $v){
                        $sub_categories[]=CategoryModel::where('id',$v)->value('name');
                    }
                }
                $data['result'][$key]['sub_category']=$sub_categories;

                if($data['result'][$key]['start_time']){
                    $data['result'][$key]['start_time']=substr($data['result'][$key]['start_time'],0,strripos($data['result'][$key]['start_time'],':'));
                    $data['result'][$key]['end_time']=substr($data['result'][$key]['end_time'],0,strripos($data['result'][$key]['end_time'],':'));
                }
            }
            //进行排序
            $sort=array_column($data['result'],'open_status');
            array_multisort($sort, SORT_ASC, $data['result']);
            $data['result']=array_slice($data['result'],($params['page']-1)*$params['pageSize'],$params['pageSize']);
        }
//        $data['iata']=$this->airportModel->where('id',$params['airport'])->value('iata');
//        $data['airport_id']=intval($params['airport']);
//        $data['terminal']=$params['terminal']?explode(',',$params['terminal']):[];
        return $data;

    }

    public function completion($params){
        if($params['scene']==2){
            //商户
            $res=$this->merchantModel->getTitle($params['keyword']);
            return array_column($res,'name');
        }else{
            //帖子
            $res=$this->postsModel->getTitle($params['keyword']);
            return array_column($res,'title');
        }
    }
}